<template>
  <div class="register-container">
    <el-card class="register-card">
      <h2 class="register-title">用户注册</h2>

      <el-form @submit.prevent="register" label-width="90px" :model="user" :rules="rules" ref="formRef">
        <el-form-item label="昵称" prop="username">
          <el-input v-model="user.username" />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="user.email" type="email" autocomplete="email" />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input v-model="user.password" type="password" show-password />
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="user.confirmPassword" type="password" show-password />
        </el-form-item>

        <el-form-item label="验证码" prop="captcha">
          <el-input v-model="user.captcha" required>
            <template #append>
              <el-button @click="sendVerificationCode" :disabled="isSending || isLoading">
                {{ codeButtonText }}
              </el-button>
            </template>
          </el-input>
        </el-form-item>

        <el-button type="primary" native-type="submit" class="register-button" :loading="isLoading">
          {{ isLoading ? '注册中...' : '立即注册' }}
        </el-button>

        <div v-if="error" class="error-message">
          {{ error }}
        </div>
      </el-form>

      <div class="login-link">
        <p>已有账号？<a href="/login">立即登录</a></p>
      </div>
    </el-card>
  </div>
</template>

<script>
import { auth } from '@/utils/api.js';

export default {
  data() {
    return {
      user: {
        username: 'zzb',
        email: '2654207269@qq.com',
        password: 'newPassword1234',
        confirmPassword: 'newPassword1234',
        captcha: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入昵称', trigger: 'blur' },
          { min: 3, max: 15, message: '昵称长度在3到15个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 8, message: '密码长度至少8位', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请确认密码', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value !== this.user.password) {
                callback(new Error('两次输入密码不一致'));
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }
        ],
        captcha: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
          { pattern: /^\d{4,6}$/, message: '请输入4-6位数字验证码', trigger: 'blur' }
        ]
      },
      isSending: false,
      codeButtonText: '获取验证码',
      countdown: 60,
      error: null,
      isLoading: false,
      storedEmail: null, // 新增：存储邮箱用于验证
      storedTimestamp: null // 新增：存储时间戳用于倒计时恢复
    }
  },
  mounted() {
    this.restoreCountdown();
  },
  watch: {
    'user.email'(newEmail) {
      if (newEmail !== this.storedEmail) {
        this.resetCountdown();
        localStorage.removeItem('verificationCodeState');
      } else {
        this.restoreCountdown();
      }
    }
  },
  methods: {
    // 重置验证码状态
    resetCountdown() {
      this.isSending = false;
      this.codeButtonText = '获取验证码';
      this.countdown = 60;
    },

    // 发送验证码
    async sendVerificationCode() {
      if (!this.user.email) {
        this.$message.error('请先填写邮箱地址');
        return;
      }

      if (!this.validateEmail(this.user.email)) {
        this.$message.error('请输入有效的邮箱地址');
        return;
      }

      this.isSending = true;
      const timer = setInterval(() => {
        if (this.countdown > 0) {
          this.codeButtonText = `${this.countdown--}秒后重试`;
        } else {
          clearInterval(timer);
          this.isSending = false;
          this.codeButtonText = '获取验证码';
          localStorage.removeItem('verificationCodeState');
        }
      }, 1000);

      try {
        await auth.sendResetCode(this.user.email);
        this.$message.success('验证码已发送');
        localStorage.setItem('verificationCodeState', JSON.stringify({
          email: this.user.email,
          timestamp: Date.now()
        }));
      } catch (error) {
        console.error('验证码请求失败', error);
        this.$message.error('获取验证码失败');
        clearInterval(timer);
        this.resetCountdown();
      }
    },

    // 恢复倒计时
    restoreCountdown() {
      const storedData = localStorage.getItem('verificationCodeState');
      if (!storedData) return;

      try {
        const { email, timestamp } = JSON.parse(storedData);
        const now = Date.now();
        const timeDiff = (now - timestamp) / 1000;

        if (email === this.user.email && timeDiff < 60) {
          this.storedEmail = email;
          this.storedTimestamp = timestamp;
          this.isSending = true;
          this.countdown = Math.max(60 - Math.floor(timeDiff), 1);
          this.codeButtonText = `${this.countdown}秒后重试`;

          const timer = setInterval(() => {
            if (this.countdown > 0) {
              this.countdown--;
              this.codeButtonText = `${this.countdown}秒后重试`;
            } else {
              clearInterval(timer);
              this.isSending = false;
              this.codeButtonText = '获取验证码';
              localStorage.removeItem('verificationCodeState');
            }
          }, 1000);
        }
      } catch (error) {
        localStorage.removeItem('verificationCodeState');
      }
    },

    // 验证邮箱格式
    validateEmail(email) {
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      return emailRegex.test(email);
    },

    // 注册逻辑
    async register() {
      this.error = null;
      try {
        // 获取表单实例
        const formRef = this.$refs.formRef;
        if (!formRef || typeof formRef.validate !== 'function') {
          throw new Error('表单实例或验证方法不存在');
        }
        await formRef.validate();
        this.isLoading = true;
        const response = await auth.register({
          email: this.user.email,
          verificationCode: this.user.captcha,
          nickname: this.user.username,
          password: this.user.password,
          confirmPassword: this.user.confirmPassword
        });
        console.log('注册接口返回：', response);
        if (response && response.message === '注册成功') {
          this.$message.success('注册成功，请登录');
          this.$router.push('/login');
        } else {
          this.error = response?.message || '注册失败，请重试';
          this.$message.error(this.error);
        }
      } catch (error) {
        console.error('注册接口异常:', error);
        this.error = error.response?.data?.message || error.message || '注册失败';
        this.$message.error(this.error);
      } finally {
        this.isLoading = false;
      }
    }
  }
};
</script>

<style>
/* 全局样式，确保按钮样式生效 */
.el-card .el-input-group__append .el-button {
  /* 默认蓝色按钮样式 */
  background-color: #409EFF !important;
  color: white !important;
  border: 1px solid #409EFF !important;
  border-radius: 4px;
  padding: 6px 12px;
}

/* 悬停状态 */
.el-card .el-input-group__append .el-button:hover {
  background-color: #3a8ee6 !important;
  border-color: #3a8ee6 !important;
}

/* 禁用状态 */
.el-card .el-input-group__append .el-button[disabled] {
  background-color: #f0f2f5 !important;
  color: #909399 !important;
  border-color: #dcdfe6 !important;
  cursor: not-allowed;
}

/* 注册页面其他样式 */
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f0f2f5;
}

.register-card {
  width: 450px;
  padding: 30px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.register-title {
  text-align: center;
  font-size: 20px;
  font-weight: 600;
  color: #333;
  margin-bottom: 24px;
}

.el-form-item {
  margin-bottom: 16px;
}

.el-input {
  width: 100%;
}

.register-button {
  width: 100%;
  margin-top: 20px;
  padding: 10px;
}

.login-link {
  margin-top: 24px;
  text-align: center;
  color: #666;
}

.login-link a {
  color: #409EFF;
  text-decoration: none;
  font-weight: 500;
}

.error-message {
  color: #ff4d4f;
  margin-top: 12px;
  text-align: center;
  font-size: 14px;
}
</style>